<template>
  <div class="search-form">
    <!-- 头部tab切换 -->
    <el-row type="flex" class="search-tab">
      <span
        v-for="(item, index) in tabs"
        :key="index"
        @click="handleSearchTab(item, index)"
        :class="{active: index === currentTab}"
      >
        <i :class="item.icon"></i>
        {{item.name}}
      </span>
    </el-row>

    <el-form :model="form" :rules="rules" class="search-form-content" ref="form" label-width="80px">
      <el-form-item label="出发城市" prop="departCity">
        <!-- el-autocomplete：可带输入建议的输入框组件 -->
        <!-- :fetch-suggestions：返回输入建议的方法属性 -->
        <el-autocomplete
          v-model="form.departCity"
          :fetch-suggestions="queryDepartCity"
          placeholder="请搜索出发城市"
          @select="handleDepartCity"
          @blur="queryDepartCity2"
          :trigger-on-focus="false"
          :highlight-first-item="true"
          class="el-autocomplete"
        ></el-autocomplete>
      </el-form-item>

      <el-form-item label="到达城市" prop="destCity">
        <el-autocomplete
          v-model="form.destCity"
          :fetch-suggestions="queryDestCity"
          placeholder="请搜索到达城市"
          @select="handleDestCity"
          @blur="queryDestCity2"
          :trigger-on-focus="false"
          :highlight-first-item="true"
          class="el-autocomplete"
        ></el-autocomplete>
      </el-form-item>

      <el-form-item label="出发时间" prop="departDate">
        <el-date-picker
          v-model="form.departDate"
          type="date"
          placeholder="选择日期"
          :picker-options="pickerOptions"
          @change="handleDate"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label>
        <el-button style="width:100%;" type="primary" icon="el-icon-search" @click="handleSubmit">搜索</el-button>
      </el-form-item>

      <div class="reverse">
        <span @click="handleExchange">换</span>
      </div>
    </el-form>
  </div>
</template>

<script>
import moment from "moment";

export default {
  data() {
    return {
      form: {
        departCity: "",
        departCode: "",
        destCity: "",
        destCode: "",
        departDate: ""
      },
      rules: {
        departCity: [
          { required: true, message: "请输入出发城市", trigger: "blur" }
        ],
        destCity: [
          { required: true, message: "请输入到达城市", trigger: "blur" }
        ],
        departDate: [
          { required: true, message: "请输入出发时间", trigger: "blur" }
        ]
      },
      tabs: [
        { icon: "iconfont icondancheng", name: "单程" },
        { icon: "iconfont iconshuangxiang", name: "往返" }
      ],
      currentTab: 0,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 3600 * 1000 * 24;
        }
      }
    };
  },
  methods: {
    // tab切换时触发
    handleSearchTab(item, index) {
      if (index == 1) {
        this.$confirm("目前暂不支持往返，请使用单程选票！", "提示", {
          confirmButtonText: "确定",
          showCancelButton: false,
          type: "warning"
        });
      }
    },

    // 封装查询出发城市和到达城市
    queryCity(value) {
      // 发送实时机票城市的请求获取后台真实数据
      return this.$axios({
        url: "/airs/city",
        params: {
          name: value
        }
      }).then(res => {
        console.log("实时出发城市的返回结果", res);

        const ListsData = res.data.data.map(city => {
          return {
            // 最后包含市字的删除掉
            value: city.name.replace(/市$/, ""),
            code: city.sort
          };
        });

        // 过滤掉所有没有code的城市
        return ListsData.filter(city => {
          return city.code;
        });
      });
    },

    // 出发城市输入框获得焦点时触发
    // value：输入建议的值
    // cb；回调函数，接收要展示的列表
    queryDepartCity(value, showLists) {
      this.queryCity(value).then(ListsData => {
        // 如果列表有值
        // 将列表的第一项设为默认的code
        if (ListsData.length > 0) {
          this.form.departCode = ListsData[0].code;

          // 显示推荐列表
          showLists(ListsData);
        } else {
          showLists([
            {
              value: "没有找到该城市"
            }
          ]);
        }
      });
    },

    // 仅填写一个字
    // 从而实现出发城市补全的需求
    queryDepartCity2(e) {
      // console.log(e.target.value);
      if (!e.target.value) {
        return;
      }

      setTimeout(() => {
        this.queryCity(e.target.value).then(ListsData => {
          // 如果列表有值
          // 将列表的第一项设为默认的code
          if (ListsData.length > 0) {
            this.form.departCity = ListsData[0].value;
          }
        });
      }, 2000);
    },

    // 到达城市输入框获取焦点
    queryDestCity(value, showLists) {
      this.queryCity(value).then(ListsData => {
        if (ListsData.length > 0) {
          this.form.destCode = ListsData[0].code;

          showLists(ListsData);
        } else {
          showLists([
            {
              value: "没有找到该城市"
            }
          ]);
        }
      });
    },

    // 仅填写一个字
    // 从而实现到达城市补全的需求
    queryDestCity2(e) {
      // console.log(e.target.value);

      if (!e.target.value) {
        return;
      }

      setTimeout(() => {
        this.queryCity(e.target.value).then(ListsData => {
          // 如果列表有值
          // 将列表的第一项设为默认的code
          if (ListsData.length > 0) {
            this.form.destCity = ListsData[0].value;
          }
        });
      }, 2000);
    },

    // 出发城市点击后选中建议项并显示
    handleDepartCity(item) {
      console.log("回调函数中展示的列表", item);

      this.form.departCode = item.code;
    },

    // 到达城市点击后选中建议项并显示
    handleDestCity(item) {
      this.form.destCode = item.code;
    },

    // 点击换时调换出发城市和到达城市
    handleExchange() {
      const OldDestCity = this.form.destCity;
      const OldDestCode = this.form.destCode;

      this.form.destCity = this.form.departCity;
      this.form.destCode = this.form.departCode;

      this.form.departCity = OldDestCity;
      this.form.departCode = OldDestCode;
    },

    // 点击确认日期时触发
    handleDate(value) {
      this.form.departDate = moment(value).format("YYYY-MM-DD");
    },

    // 点击提交按钮时触发
    handleSubmit() {
      //   console.log(this.form);

      // 整个表单校验
      this.$refs.form.validate((isPass, objNotPass) => {
        console.log(isPass);
        console.log(objNotPass);
        console.log(this.form);
        if (isPass) {
          this.$router.push({
            path: "/air/flights",
            query: this.form
          });

          // 将query的五个参数发射去vuex中存储起来
          // 以便历史记录获取参数数据进行遍历
          this.$store.commit("history/setHistory", this.form);
        } else {
          console.log(objNotPass);
        }
      });
    }
  },
  mounted() {}
};
</script>

<style scoped lang="less">
.search-form {
  border: 1px #ddd solid;
  border-top: none;
  width: 360px;
  height: 350px;
  box-sizing: border-box;
  background-color: #fff;
}

.search-tab {
  span {
    display: block;
    flex: 1;
    text-align: center;
    height: 48px;
    line-height: 42px;
    box-sizing: border-box;
    border-top: 3px #eee solid;
    background: #eee;
  }

  .active {
    border-top-color: orange;
    background: #fff;
  }

  i {
    margin-right: 5px;
    font-size: 18px;

    &:first-child {
      font-size: 16px;
    }
  }
}

.search-form-content {
  padding: 15px 50px 15px 15px;
  position: relative;

  .el-autocomplete {
    width: 100%;
  }
}

.reverse {
  position: absolute;
  top: 35px;
  right: 15px;

  &:after,
  &:before {
    display: block;
    content: "";
    position: absolute;
    left: -35px;
    width: 25px;
    height: 1px;
    background: #ccc;
  }

  &:after {
    top: 0;
  }

  &:before {
    top: 60px;
  }

  span {
    display: block;
    position: absolute;
    top: 20px;
    right: 0;
    font-size: 12px;
    background: #999;
    color: #fff;
    width: 20px;
    height: 20px;
    line-height: 18px;
    text-align: center;
    border-radius: 2px;
    cursor: pointer;

    &:after,
    &:before {
      display: block;
      content: "";
      position: absolute;
      left: 10px;
      width: 1px;
      height: 20px;
      background: #ccc;
    }

    &:after {
      top: -20px;
    }

    &:before {
      top: 20px;
    }
  }
}
</style>